package com.service.pub;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpExchange;


public class ParameterFilter extends Filter 
{
	private String encoding = "utf-8";
	
    public ParameterFilter()
    {
    }
    
    public ParameterFilter(String encoding)
    {
    	this.encoding = encoding;
    }
    
	@Override
    public String description() 
    {
        return "Parses the requested URI for parameters";
    }

    @Override
    public void doFilter(HttpExchange exchange, Chain chain) throws IOException 
    {
        parseGetParameters(exchange);
        parsePostParameters(exchange);
        chain.doFilter(exchange);
    }    

    private void parseGetParameters(HttpExchange exchange) throws UnsupportedEncodingException 
    {

        Map<String, Object> parameters = new HashMap<String, Object>();
        URI requestedUri = exchange.getRequestURI();
        
        String query = requestedUri.getRawQuery();
        
//        System.out.println("query = " + query);
        
        parseQuery(query, parameters);
        exchange.setAttribute("parameters", parameters);
    }

    @SuppressWarnings("unchecked")
	private void parsePostParameters(HttpExchange exchange) throws IOException 
    {
        if ("post".equalsIgnoreCase(exchange.getRequestMethod())) {
            Map<String, Object> parameters = (Map<String, Object>)exchange.getAttribute("parameters");
            InputStreamReader isr 	= new InputStreamReader(exchange.getRequestBody(), encoding);
            BufferedReader br 		= new BufferedReader(isr);
            String query 			= br.readLine();
            parseQuery(query, parameters);
        }
    }

     @SuppressWarnings("unchecked")
     private void parseQuery(String query, Map<String, Object> parameters) throws UnsupportedEncodingException 
     {
         if (query != null) {
        	 String key, value;
        	 
             String[] param, pairs;
             
             Object obj;
             List<String> values;
             
        	 pairs = query.split("[&]");
             
             for (String pair : pairs) {
                 param = pair.split("[=]");

                 key 	= null;
                 value 	= null;
                 if (param.length > 0) {
                     key = URLDecoder.decode(param[0], System.getProperty("file.encoding"));
                 }

                 if (param.length > 1) {
                     value = URLDecoder.decode(param[1], System.getProperty("file.encoding"));
                 }

                 if (parameters.containsKey(key)) {
                     obj = parameters.get(key);
                     if(obj instanceof List<?>) {
                         values = (List<String>)obj;
                         values.add(value);
                     } else if(obj instanceof String) {
                         values = new ArrayList<String>();
                         values.add((String)obj);
                         values.add(value);
                         parameters.put(key, values);
                     }
                 } else {
                     parameters.put(key, value);
                 }
             }
         }
    }
}